package com.liuzhilong.infrastructure.basic.file;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

import static com.liuzhilong.infrastructure.basic.file.FileTestConstant.*;

public class FileCopyIO {

    /**
     * 传统流的方式进行copy
     *
     * @param src
     * @param dist
     */
    public static final void copyByStream(File src, File dist) throws IOException {
        long start = System.currentTimeMillis();
        System.out.println("开始复制:"+start);
        byte[] bytes = new byte[fullChar.getBytes(StandardCharsets.UTF_8).length];
        try (InputStream in = new FileInputStream(src);
             OutputStream outputStream = new FileOutputStream(dist)
        ) {
            while (in.read(bytes)>-0){
                outputStream.write(bytes);
            }
        }
        System.out.println("结束复制:"+System.currentTimeMillis()+",耗时"+(System.currentTimeMillis()-start));

    }

    /**
     * 传统流的方式进行copy
     *
     * @param src
     * @param dist
     */
    public static final void copyByBuffer(File src, File dist) throws IOException {
        long start = System.currentTimeMillis();
        System.out.println("开始复制:"+start);
        byte[] bytes = new byte[fullChar.getBytes(StandardCharsets.UTF_8).length];
        try (InputStream in = new BufferedInputStream( new FileInputStream(src));
             OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(dist))
        ) {
            while (in.read(bytes)>-0){
                outputStream.write(bytes);
            }
        }
        System.out.println("结束复制:"+System.currentTimeMillis()+",耗时"+(System.currentTimeMillis()-start));

    }
    /**
     * 传统流的方式进行copy
     *
     * @param src
     * @param dist
     */
    public static final void copyByChannel(File src, File dist) throws IOException {
        long start = System.currentTimeMillis();
        System.out.println("开始复制:"+start);
        FileChannel srcChannel=new FileInputStream(src).getChannel();
        FileChannel distChannel= new RandomAccessFile(dist,"rw").getChannel();
        srcChannel.transferTo(0, srcChannel.size(), distChannel);
        System.out.println("结束复制:"+System.currentTimeMillis()+",耗时"+(System.currentTimeMillis()-start));

    }
    public static void main(String[] args) throws IOException {
        File src = FileSimpleIO.createFile("test" + System.currentTimeMillis() + "1");
        File dist = FileSimpleIO.createFile("test" + System.currentTimeMillis() + "2");
        FileSimpleIO.writeByChannel(src);
        copyByChannel(src, dist);
    }


}
